package com.zansc.longd.config.shiro;

import com.zansc.longd.domain.entity.s.User;
import com.zansc.longd.model.base.bean.ActiveUser;
import com.zansc.longd.service.s.UserService;
import com.zansc.longd.utils.JWTUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MyRealm extends AuthorizingRealm {
    
    @Autowired
    private UserService userService;
    
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof ShiroToken;
    }
    
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }
    
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken shiroToken) throws AuthenticationException {
        String token = (String) shiroToken.getCredentials();
        String username = JWTUtils.getUsername(token);
        if (username == null) {
            throw new AuthenticationException("用户错误，请重新登录！");
        }
        
        User userByName = userService.findUserByName(username);
        
        if (userByName == null) {
            throw new AccountException("用户不存在，请重新登录！");
        }
        
        if (JWTUtils.isExpires(token)) {
            throw new AuthenticationException(" token过期，请重新登入！");
        }
        
        if (!JWTUtils.verify(token, username, userByName.getPassword())) {
            throw new CredentialsException("密码错误!");
        }
        
        if(userByName.getStatus()==1){
            throw new LockedAccountException("账号已被锁定!");
        }
    
        return new SimpleAuthenticationInfo(new ActiveUser(username), token, this.getName());
    }
}
